package com.xialj.demoend.controller;

import cn.hutool.core.util.StrUtil;
import com.xialj.demoend.common.Result;
import com.xialj.demoend.entity.User;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.Optional;
import java.util.function.Supplier;

/**
 * @Author xlj
 * @Date Created in  2023/3/18 14:30
 * @DESCRIPTION:
 * @Version V1.0
 */
@RestController
@RequestMapping("/user/login")
@Slf4j
@CrossOrigin
public class LoginController {
   @Autowired
   private RedisTemplate<String,String> redisTemplate;
   @ApiOperation("手机验证码登录接口")
   @PostMapping("/phoneCode")
   @SuppressWarnings("all")
   public Result phoneCodeLogin(@RequestBody @Validated User user) throws Throwable {
      Optional.ofNullable(user.getPhone()).orElseThrow((Supplier<Throwable>) () -> new RuntimeException("手机号码为null"));
      String phone = user.getPhone();
      log.info("当前获取的手机号为:{}",phone);
      //从redis中获取手机验证码
      String userPhoneKey = redisTemplate.opsForValue().get(phone);
      if (StringUtils.isEmpty(userPhoneKey)) {
         return Result.fail("手机验证码有误");
      }
      if (!userPhoneKey.equals(String.valueOf(user.getCode()))) {
         return Result.fail("手机验证码有误");
      }
      return Result.ok("登录成功");
   }
   @ApiOperation("手机验证码登录接口")
   @PostMapping("/emailCode")
   public Result emailCodeLogin(@RequestBody @Validated User user) throws Throwable {
      String email = user.getEmail();
      if (StrUtil.isEmpty(email)){
         throw new Exception("邮箱错误!");
      }
      log.info("当前获取的邮箱为:{}",email);
      //从redis中获取手机验证码
      String emailCode = redisTemplate.opsForValue().get(email);
      if (StringUtils.isEmpty(emailCode)) {
         return Result.fail("邮箱验证码有误");
      }
      if (!emailCode.equals(String.valueOf(user.getCode()))) {
         return Result.fail("邮箱验证码有误");
      }
      return Result.ok("登录成功");
   }
}
